from common import get_logger, browser
from DrissionPage.common import Keys

logger = get_logger(__name__)


def post_to_bjh(title, intro, img_paths):
    extra_info = "无"
    try:
        # 记录开始发布百家号的日志信息，包含标题和图片路径
        logger.info(f"准备自动发到百家号，标题：{title}，图片：{img_paths}")
        # 打开百度百家号写作页面
        tab = browser.new_tab(
            "https://baijiahao.baidu.com/builder/rc/edit?type=news&is_from_cms=1"
        )
        # 等待页面加载完成
        tab.wait(3)
        # 清空缓存
        tab.run_js("localStorage.clear(); sessionStorage.clear();")
        tab.wait(1)
        # 刷新页面
        tab.refresh()
        # 等待页面加载完成
        tab.wait(3)

        # 检查标题长度是否2-30个字符，如果超过则截取前30个字符
        if len(title) < 2:
            return
        if len(title) > 30:
            title = title[:30]

        title_input = tab("tag:textarea@class:cheetah-input", timeout=30)
        title_input.input(title)
        # 输入新内容
        tab.wait(1)

        # 查找正文输入区域元素，使用DraftEditor-root类选择器
        iframe = tab.get_frame("tag:iframe@id:ueditor_0", timeout=10)
        # iframe.run_js('document.querySelector("body.news-editor-pc").innerHTML = ""')
        tab.wait(0.5)
        intro_editor = iframe("tag:body@class:news-editor-pc", timeout=10)
        intro_editor.click()
        # 在正文输入区域中输入正文内容
        tab.actions.type(intro)
        # 按回车键换行 模拟键盘点击，解决已有输入内容自动被清空的问题
        tab.actions.key_down("Shift")
        tab.actions.key_down("Enter")
        tab.actions.key_up("Enter")
        tab.actions.key_up("Shift")
        tab.wait(1)

        # 设置要上传的图片文件路径，多个路径用换行符分隔
        tab.set.upload_files("\n".join(img_paths))

        # 点击插入图片
        insert_btn = tab("tag:div@class:mG_E_WS8reWhDLDvuPOv", timeout=10)
        insert_btn.hover()
        insert_img_btn = tab("tag:div@class:lgKe7q02sAHqvpp1GohY", timeout=10)
        insert_img_btn.click()
        tab("tag:div@class:cheetah-tabs-tab-btn").hover()
        upload_btn = tab("tag:div@class:uploader-inner", timeout=10)
        upload_btn.click()

        # 等待图片上传完成
        tab.wait(5)

        modal_box = tab("tag:div@class:cheetah-modal-content", timeout=10)
        confirm_btn = modal_box.ele("tag:span@text()=确认", timeout=10)
        confirm_btn.click()
        tab.wait(1)

        set_box = tab("tag:div@id=bjhEditWrapSet", timeout=10)
        radio_btn = set_box.ele(
            "tag:input@@class:cheetah-radio-input@@value=one", timeout=10
        )
        radio_btn.click()
        tab.wait(1)

        # 设置封面
        cover_uploader_view = tab("tag:div@class:coverUploaderView", timeout=10)
        cover_uploader_view.click()
        tab.wait(1)
        modal_choose_cover = tab(
            "tag:div@class:cheetah-ui-pro-image-modal-choose-cover"
        )
        cover_item = modal_choose_cover("tag:div@class:item", timeout=10)
        cover_item.click()
        tab.wait(1)
        edit_btn = tab("tag:button@id=imageModalEditBtn")
        edit_btn.click()
        tab.wait(1)
        edit_box = tab("tag:div@class:MFRna", timeout=10)
        tailor_btn = edit_box("tag:li@class:CMZ9s")
        tailor_btn.click()
        tab.wait(1)
        kld_x = tab("tag:div@class:kld-X")
        finish_btn = kld_x("tag:div@role=confirm")
        finish_btn.click()
        tab.wait(1)
        tailor_finish_btn = tab("tag:button@class:_7Ojif")
        tailor_finish_btn.click()
        tab.wait(1)

        popover_box = tab("tag:div@class:cheetah-popover-inner-content", timeout=10)
        svg_btn = popover_box.ele(
            "tag:svg@xmlns=http://www.w3.org/2000/svg", timeout=10
        )
        svg_btn.click()
        tab.wait(1)

        checkbox_btn = set_box.ele("tag:span@text()=AI创作声明")
        checkbox_btn.click()
        tab.wait(1)

        publish_btn_wrap = tab("tag:div@class:BWpEGkCHbl31nFuxMzeX", timeout=10)

        publish_btn = publish_btn_wrap("tag:span@text()=发布", timeout=30)
        publish_btn.click()
        # 等待发布完成
        tab.wait(3)
        # 记录发布成功的日志信息
        logger.info("百家号发布成功~~")
        status = 1
    except Exception as e:
        status = 2
        extra_info = str(e)
        logger.error(extra_info)
    return {"status": status, "extra_info": extra_info}
